package com.mango.amazon;


import com.alibaba.fastjson.JSONObject;
import com.amazon.spapi.feeds_2021_06_30.ApiException;
import com.amazon.spapi.feeds_2021_06_30.model.*;
import com.github.fge.jsonschema.core.exceptions.ProcessingException;
import com.mango.amazon.convert.FeedsConvert;
import com.mango.amazon.entity.FeedsEntity;
import com.mango.amazon.entity.Inventory;
import com.mango.amazon.util.JsonSchemaUtil;
import com.mango.amazon.util.UploadOrDownloadExample;
import org.springframework.stereotype.Service;

import javax.xml.bind.Marshaller;
import java.io.IOException;

@Service
public class FeedsService {
    String str = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
            "<AmazonEnvelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"amznenvelope.xsd\">\n" +
            "<Header>\n" +
            "<DocumentVersion>1.01</DocumentVersion>\n" +
            "<MerchantIdentifier>M_SELLER_354577</MerchantIdentifier>\n" +
            "</Header>\n" +
            "<MessageType>Inventory</MessageType>\n" +
            "<Message>\n" +
            "<MessageID>1</MessageID>\n" +
            "<OperationType>Update</OperationType>\n" +
            "<Inventory>\n" +
            "<SKU>TEST-SKU-ZI-11</SKU>\n" +
            "<Quantity>8</Quantity>\n" +
            "<FulfillmentLatency>1</FulfillmentLatency>\n" +
            "</Inventory>\n" +
            "</Message>\n" +
            "</AmazonEnvelope>";


    /**
     * 创建产品
     */
    public void publishProduct(FeedsEntity entity) throws ApiException, InterruptedException, IOException, ProcessingException, com.amazon.spapi.definitionsProductTypes_2020_09_01.ApiException {
        //步骤一: 获取FeedId + URL
        CreateFeedDocumentSpecification specification = FeedsConvert.toCreateFeedDocumentSpecification(entity);
        CreateFeedDocumentResponse feedDocument = APIfactory.feedsApi.createFeedDocument(specification);
        //步骤二:构建提要并上传
        //  SchemaLoaderUtil.validJson((JSONObject) JSONObject.toJSON(entity.getRoot()));

        UploadOrDownloadExample.upload(JSONObject.toJSONString(entity.getRoot()), feedDocument.getUrl());

       /* boolean processingReport = JsonSchemaUtil.getProcessingReport(JsonSchemaUtil.strToJsonNode(JSONObject.toJSONString(entity.getRoot())), JsonSchemaUtil.getJsonSchemaNode());
        System.out.println(processingReport);*/


        // UploadOrDownloadExample.upload(str, feedDocument.getUrl());
        //步骤三
        CreateFeedSpecification createFeedSpecification = FeedsConvert.toCreateFeedSpecification(entity, feedDocument);
        CreateFeedResponse feed = APIfactory.feedsApi.createFeed(createFeedSpecification);
        //步骤四: 查询结果 - 定期调用
        Feed feedResult = RegularGetFeed(feed.getFeedId());
        //步骤五:获取处理结果链接+算法
        FeedDocument feedDocumentResult = APIfactory.feedsApi.getFeedDocument(feedResult.getResultFeedDocumentId());
        //步骤六:下载结果
        String sss = null;
        if (feedDocumentResult.getCompressionAlgorithm() != null) {
            sss = feedDocumentResult.getCompressionAlgorithm().getValue();
        }
        UploadOrDownloadExample.download(feedDocumentResult.getUrl(), sss);
        //更新库存


        System.out.println("成");

    }

    public Feed RegularGetFeed(String feedId) throws InterruptedException, ApiException {
        Feed apiFeed = null;
        int i = 0;
        do {
            Thread.sleep(3000);
            apiFeed = APIfactory.feedsApi.getFeed(feedId);
            if (apiFeed == null) {
                break;
            }
            if (i++ > 5) {
                System.err.println("请求Feed结果超过次数");
            }
        } while (!Feed.ProcessingStatusEnum.DONE.equals(apiFeed.getProcessingStatus()));
        return apiFeed;
    }


    public void updateInventory(Inventory inventory, FeedsEntity entity) throws ApiException, InterruptedException, IOException {
        //步骤一: 获取FeedId + URL
        CreateFeedDocumentSpecification specification = FeedsConvert.toCreateFeedDocumentSpecification(null);
        CreateFeedDocumentResponse feedDocument = APIfactory.feedsApi.createFeedDocument(specification);
        //步骤二:构建提要并上传
        String xml = str;//FeedsConvert.entity2XML(inventory);
        System.out.println(xml);
        UploadOrDownloadExample.upload(xml, feedDocument.getUrl());

        //步骤三
        CreateFeedSpecification createFeedSpecification = FeedsConvert.toCreateFeedSpecification(entity, feedDocument);
        CreateFeedResponse feed = APIfactory.feedsApi.createFeed(createFeedSpecification);
        //步骤四: 查询结果 - 定期调用
        Feed feedResult = RegularGetFeed(feed.getFeedId());
        //步骤五:获取处理结果链接+算法
        FeedDocument feedDocumentResult = APIfactory.feedsApi.getFeedDocument(feedResult.getResultFeedDocumentId());
        //步骤六:下载结果
        String sss = null;
        if (feedDocumentResult.getCompressionAlgorithm() != null) {
            sss = feedDocumentResult.getCompressionAlgorithm().getValue();
        }
        UploadOrDownloadExample.download(feedDocumentResult.getUrl(), sss);
        //更新库存


        System.out.println("成");
    }
}
